package com.sfdcj.se.meta.field;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Set;

import com.sforce.soap._2006._04.metadata.CustomField;
import com.sforce.soap._2006._04.metadata.Picklist;
import com.sforce.soap._2006._04.metadata.PicklistValue;

public class PickListType extends FieldType {

	static final String TYPE = "Picklist";

	List<String> fullNames;

	public PickListType() {
		super();
		fullNames = new ArrayList<String>();
	}

	public void addPicklistValue(String fullName) {
		fullNames.add(fullName);
	}

	public void appendXML() {
		buf.append("<picklist>");
		for (String name : fullNames) {
			buf.append("<picklistValues>");
			buf.append("<fullName>" + name + "</fullName>");
			buf.append("<default>false</default>");
			buf.append("</picklistValues>");
		}
		buf.append("<sorted>false</sorted>");
		buf.append("</picklist>");
		buf.append("<type>" + TYPE + "</type>");
	}

	@Override
	public String getTypeName() {
		return TYPE;
	}

	@Override
	public Object clone() {
		return new PickListType();
	}

	@Override
	public void setAttributes(HashMap<String, String> attributes) {
		Set<String> keys = attributes.keySet();
		Iterator<String> itr = keys.iterator();
		while (itr.hasNext()) {
			String key = itr.next();
			if (!key.startsWith("fullName")) {
				continue;
			}
			addPicklistValue(attributes.get(key));
		}
	}

	@Override
	public CustomField toCustomField() {
		CustomField field = new CustomField();
		field.setFullName(objectFullname + "." + fullname);
		field.setLabel(label);

		List<PicklistValue> vars = new ArrayList<PicklistValue>();
		for (String name : fullNames) {
			PicklistValue value = new PicklistValue();
			value.setFullName(name);
			vars.add(value);
		}

		Picklist list = new Picklist();
		list.setPicklistValues((PicklistValue[]) vars.toArray(new PicklistValue[vars.size()]));
		field.setPicklist(list);
		
		field.setType(com.sforce.soap._2006._04.metadata.FieldType.Picklist);
		return field;
	}
}
